package com.liu.manag.granter;

import com.liu.manag.entity.User;
import com.liu.manag.security.MyUserDetailsService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

import java.util.*;

public class UsernamePasswordUserTokenGranter extends AbstractUserTokenGranter {
    protected MyUserDetailsService userDetailsService;
    private final OAuth2RequestFactory requestFactory;
    public  UsernamePasswordUserTokenGranter(MyUserDetailsService userDetailsService,AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory) {
        super(tokenServices, clientDetailsService, requestFactory, "pwd");
        this.requestFactory = requestFactory;
        this.userDetailsService = userDetailsService;
    }

    @Override
    protected User getUser(Map<String, String> parameters) {
        String username = parameters.get("username");
        String password = parameters.get("password");
        if(username.matches(".*@.*")){
            String email = username;
            return userDetailsService.loadUserByEmailAndSms(email,"123");
        }else{
            User user =  userDetailsService.loadUserByUsernameAndPassword(username, password);
            Collection<GrantedAuthority> authorities = new ArrayList<>(Arrays.asList(
                    new SimpleGrantedAuthority(
                            "ROLE_" + "admin"),
                    new SimpleGrantedAuthority(
                            "ROLE_" + "user")
            ));
            user.setAuthorities(authorities);
            return user;
        }

    }

//    @Override
//    protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
//        OAuth2Request storedOAuth2Request = requestFactory.createOAuth2Request(client, tokenRequest);
//        Collection<GrantedAuthority> authorities = new ArrayList<>(Arrays.asList(
//                new SimpleGrantedAuthority(
//                        "ROLE_" + "admin"),
//                new SimpleGrantedAuthority(
//                        "ROLE_" + "user")
//        ));
//        return new OAuth2Authentication(storedOAuth2Request, );
//    }
}
